package com.summba.analysis;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.dbutils.ResultSetHandler;

import com.summba.common.Common;
import com.summba.mysql.dao.DaoBase;
import com.summba.mysql.dao.DataSourceFactory;

public class StatisticsCFCrawlCount extends DaoBase {
	
	private Map<String,Integer> keywordsCountMapper = new HashMap<String, Integer>();

	public StatisticsCFCrawlCount() throws Exception{
		setDataSource(DataSourceFactory.getDataSource());
		getAllKeywords();
		showResult(keywordsCountMapper);
	}
	
	public void getAllKeywords() throws Exception{
		String queryKeywordCount = "select keywords,count(id) from " +
				"wb_tag_message group by keywords order by count(id) desc";
		ResultSetHandler< Map<String,Integer> > queryKeywordCountHandler = 
			new ResultSetHandler< Map<String,Integer> >(){

				@Override
				public Map<String, Integer> handle(ResultSet rs)
						throws SQLException {
					Map<String,Integer> tempMapper = new HashMap<String, Integer>();
					while(rs.next()){
						tempMapper.put(rs.getString(1), rs.getInt(2));
					}
					
					return tempMapper;
				}
			
		};
		keywordsCountMapper = findBean(queryKeywordCount,queryKeywordCountHandler);		
	}
	
	public void showResult( Map<String, Integer> wordMapper){
		List<Map.Entry<String, Integer>> infoIds = 
			new ArrayList< Map.Entry<String, Integer> >(keywordsCountMapper.entrySet());
		
		Comparator <Map.Entry<String, Integer>> comparator = new Comparator<Map.Entry<String, Integer>>(){

			@Override
			public int compare(Entry<String, Integer> o1,
					Entry<String, Integer> o2) {
				return (o2.getValue() - o1.getValue()); 
			}
			
		};
		
		Collections.sort(infoIds, comparator);
		for (int i = 0; i < infoIds.size(); i++) { 
			String id = infoIds.get(i).toString();
			Common.appendFile("D:\\work\\summba.src\\weibo_analysiscorpus\\" +
					"result\\cfKeywordCount.sdb", id+ "\n");
			System.out.println(id); 
		}
	}

}
